// pages/userMarket/userMarket.js
const app = getApp()
const WXAPI = require("../../api/api")
const WXAPIOLD = require("../../api/api")
const WXNEWAPI = require("../../api/newApi")
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    screening: [{
        id: 1,
        value: '推荐商家'
      },
      {
        id: 2,
        value: '离我最近'
      },
    ],
    navType: [{
        id: 0,
        url: './images/nav_1.png',
        value: '所有商家'
      },
      {
        id: 1,
        url: './images/nav_2.png',
        value: '预付卡查询'
      },
      {
        id: 2,
        url: './images/nav_3.png',
        value: '预付卡监管'
      },
      {
        id: 3,
        url: './images/nav_4.png',
        value: '我的预付卡'
      },
    ],
    btList: [{
        id: 1,
        value: '推荐商家'
      },
      {
        id: 2,
        value: '离我最近'
      },
    ],
    queryType: 1,
    shopImgList: [
      // {id: 2,url:'https://kayouyou-1257308601.cos.ap-guangzhou.myqcloud.com/3be78f07f84c41bd8c16b7a2e2f5a0ee.png'},
      // {
      //   id: 3,
      //   url: 'https://kayouyou-1257308601.cos.ap-guangzhou.myqcloud.com/3f823b22b9954d618081b927d9cf9574.jpg'
      // },
      // {
      //   id: 0,
      //   url: 'https://kayouyou-1257308601.cos.ap-guangzhou.myqcloud.com/6226c9fc36bf4d8b85b626cd3f669099.jpg'
      // },
      // {
      //   id: 1,
      //   url: 'https://kayouyou-1257308601.cos.ap-guangzhou.myqcloud.com/61859d23e30f48f5bfecd890c92ad291.jpg'
      // },
      // {
      //   id: 4,
      //   url: 'https://kayouyou-1257308601.cos.ap-guangzhou.myqcloud.com/d53f789dbe954112a10b97e9d1f2c662.jpg'
      // },
      // {
      //   id: 5,
      //   url: 'https://kayouyou-1257308601.cos.ap-guangzhou.myqcloud.com/5a947803eabe40349bde1ebbb20e854d.jpg'
      // },
    ],
    imgHttp: app.globalData.imgHttp, //图片前缀
    pageSize: 10,
    pageNum: 1,
    lnt: '', //经度
    lat: '', //纬度
    areaCode: '460100',
    cardList: [],
    pages: '', //总页数
    address: '', //根据定位获取的地址
    chooseaddr: '海口市', //选择地址
    scrollY: false,
    scroll_height: '',
    backgroundColor: '',
    opacity: '',
    isUpgrade: false, //版本热更新
    addrShow: false, //选择地址弹窗
    addresType: [],
    unauthorized: true, //未授权位置
    permissions_Addr: false,
    isPull: true, //是否刷新
    lodingtype: 0, //加载状态（0：加载中  1：加载完成没有更多）
    staffId: '',
    levelTipShow: false, //等级说明弹窗
    tipShow: false,//签约保险说明弹窗
    superviseTipShow: false,//资金监管弹窗
    superviseRatio: 0,//资金监管数额
  },
  suijishu() {
    var a = Math.floor(Math.random() * (8 - 0));
    console.log(a)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getupdate()
    qqmapsdk = new QQMapWX({
      key: '5TMBZ-NASKV-ER5PO-ULIJO-CE6MZ-O4BAQ'
    });
    // this.view_height()
    this.getDict()
    this.setNavSize()
    this.isGetSetting()
    
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('token') != ''&&wx.getStorageSync('token') != undefined) {
      this.getMyCard()
    } else {
      this.setData({
        ['navType[3].value']: '我的预付卡(0)'
      })
    }
    this.getBannerLs()
  },
  //获取首页轮播图
  getBannerLs() {
    var data = {
      city: this.data.areaCode
    }
    WXNEWAPI.bannerList(data, (res) => {
      if (res.code == 200) {
        this.setData({
          shopImgList: res.result
        })
      }
    })
  },
  //获取地区
  getDict() {
    WXAPI.getCityList('', (res) => {
      const data = res.result
      if (res.code === 200) {
        this.setData({
          addresType: data
        })

      }
    })
  },
  getupdate() { //请求版本更新提示
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate((res) => {
      // 请求完新版本信息的回调
      console.log('是否有版本更新++++++', res.hasUpdate)
      if (res.hasUpdate == true) {
        wx.hideTabBar({
          animation: false,
        })
        this.setData({
          isUpgrade: true,
        })
      }
    })
    updateManager.onUpdateFailed(function () {
      wx.showTabBar({
        animation: false,
      })
      // 新版本下载失败
      wx.showModal({
        title: '已经有新版本了哟~',
        content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
      })
    })
  },

  //点击更新版本
  toUpdate() {
    console.log('点击更新')
    let updateManager = wx.getUpdateManager()
    updateManager.applyUpdate()
    updateManager.onUpdateFailed(function () {
      wx.showTabBar({
        animation: false,
      })
      // 新版本下载失败
      wx.showModal({
        title: '已经有新版本了哟~',
        content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
      })
    })
  },
  //选择地址
  handleAddr() {
    this.setData({
      addrShow: true,
    })
  },
  handleChose() {
    this.setData({
      addrShow: false,
    })
  },
  //区域选择
  handlesuccess(e) {
    console.log('eeeeeeeee', e.detail)
    this.setData({
      areaCode: e.detail.code,
      pageNum: 1,
      addrShow: false,
      chooseaddr: e.detail.value,
      cardList: [],
    })
    this.getBannerLs()
    this.getList()
  },
  getMyCard() { //获取我的预付卡(使用中)
    var data = {
      pageNum: 1,
      pageSize: 10,
      status: 1,
    }
    WXNEWAPI.cardList(data, (res) => {
      if (res.code == 200) {
        this.setData({
          ['navType[3].value']: '我的预付卡(' + res.result.total + ')'
        })
      } else {
        this.setData({
          ['navType[3].value']: '我的预付卡(0)'
        })
      }
    })
  },
  //搜索
  handleSearch() {
    wx.navigateTo({
      url: '/userPageB/pages/userMarket/searchFor/searchFor',
    })
  },

  handleBt(e) {
    var id = e.currentTarget.dataset.id
    this.setData({
      queryType: id,
      pageNum: 1,
      cardList: [],
    })
    this.getList()
  },
  handleswiper(e) {
    var item = e.currentTarget.dataset.item
    if (item.redirectType == 2) { //跳转h5页面
      if (item.redirectUrl=='') {
        return
      }
      wx.navigateTo({
        url: '/userPageB/pages/userMarket/regulatory/regulatory?url=' + item.redirectUrl,
      })
    } else if (item.redirectType == 3) { //跳转其他小程序
      if (item.redirectUrl==''||item.appId=='') {
        return
      }
      wx.navigateToMiniProgram({
        appId: item.appId,
        path: item.redirectUrl,
        extraData: {
          // 传递给跳转的小程序的数据，可选
        },
        success(res) {// 成功跳转到小程序的回调函数
          console.log(res)
        },
        fail(res) {// 跳转到小程序失败的回调函数
          console.log(res)
        },
        complete(res) {// 不论跳转成功或失败都会执行的回调函数
          console.log(res)
        }
      });
    } else { //本小程序页面
      if (item.redirectUrl=='') {
        return
      }
      wx.reLaunch({
        url: item.redirectUrl,
      })
    }
    // var id = e.currentTarget.dataset.id
    // if (id == 1) {
    //   wx.navigateTo({
    //     url: '/userPageB/pages/userMarket/regulatory/regulatory',
    //   })
    // } else if (id == 4) {
    //   this.setData({
    //     levelTipShow: true
    //   })
    // } else if (id == 5) {
    //   wx.navigateTo({
    //     url: '/userPageB/pages/userMarket/regulatory/regulatory?openType=' + '1',
    //   })
    // }
  },
  //跳转卖场
  // handleStores(e){
  //   wx.navigateTo({
  //     url: '/userPageB/pages/userMarket/storesList/storesList',
  //   })
  // },
  //跳转分类商家
  handleClass(e) {
    let id = e.currentTarget.dataset.id
    let name = e.currentTarget.dataset.name
    if (id == 0) {
      id = ''
      wx.navigateTo({
        url: '/userPageB/pages/userMarket/merchantsList/merchantsList?id=' + id + '&name=' + name,
      })
    } else if (id == 1) {
      wx.navigateTo({
        url: '/userPageA/pages/creditCardSear/creditCardSear',
      })
    } else if (id == 2) {
      // wx.navigateTo({
      //   url: '/userPageB/pages/userMarket/regulatory/regulatory?url=' + app.globalData.superviseHttp,
      // })
      wx.reLaunch ({
        url: '/govSuperviseTourist/pages/superviseIndex/superviseIndex'
      })
    } else if (id == 3) {
      if (wx.getStorageSync('token') == '') {
        wx.showToast({
          title: '请登录后查看',
          icon: 'none'
        })
        return
      }
      wx.navigateTo({
        url: '/ecCanvas/pages/myShareholderCard/allCard/allCard',
      })
    }

  },
  //跳转店铺
  handleShop(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/userPageB/pages/userStore/storesDetails/storesDetails?shopId=' + id,
    })
  },
  //跳转卡详情
  handleCard(e) {
    var id = e.currentTarget.dataset.id
    var merchantId = e.currentTarget.dataset.merchantid
    wx.navigateTo({
      url: '/userPageB/pages/userStore/cardDetail/cardDetail?assetId=' + id + '&merchantId=' + merchantId,
    })
  },
  //获取位置授权
  isGetSetting() {
    wx.showLoading({
      title: '位置获取中',
      mask: true,
    })
    var that = this;
    // 判断用户是否授权
    wx.getSetting({
      success: (res) => {
        var statu = res.authSetting;
        console.log('statu2', statu)
        if (!statu['scope.userLocation']) { //没授权
          //1、获取当前位置坐标
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              console.log("经纬度", res)
              app.globalData.lat = res.latitude //维度
              app.globalData.lnt = res.longitude //经度
              qqmapsdk.reverseGeocoder({
                location: {
                  latitude: res.latitude,
                  longitude: res.longitude,
                },
                success: function (res) {
                  console.log('地址', res)
                  that.setData({
                    address: res.result.formatted_addresses.recommend
                  })
                }
              })
              that.setData({
                lat: res.latitude, //维度
                lnt: res.longitude, //经度
                unauthorized: true,
              })
              that.judgeArrd()
              that.getList()
            },
            fail: function (res) {
              that.getList()
              that.setData({
                unauthorized: false,
              })
            },
          })
        } else {
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              console.log("经纬度", res)
              app.globalData.lat = res.latitude //维度
              app.globalData.lnt = res.longitude //经度
              that.setData({
                lat: res.latitude, //维度
                lnt: res.longitude, //经度
                unauthorized: true,
              })
              // qqmapsdk.reverseGeocoder({
              //   location: {
              //     latitude: res.latitude,
              //     longitude: res.longitude
              //   },
              //   success: function (res) {
              //     console.log('地址', res)
              //     that.setData({
              //       address: res.result.formatted_addresses.recommend
              //     })
              //   }
              // })
              that.getList()
            },
            fail: function (res) {
              that.getList()
              that.setData({
                unauthorized: false,
              })
            },
          })
        }
      },
      fail: function (res) {
        // wx.hideLoading();
      },
    })
  },
  //切换tabar
  onTabItemTap(item) {
    this.judgeArrd()
  },
  //判断是否开启位置
  judgeArrd() {
    var that = this
    wx.getSetting({
      success: (res) => {
        var statu = res.authSetting;
        console.log('statu', statu)
        if (!statu['scope.userLocation']) { //未授权
          console.log('未授权位置信息')
          that.setData({
            permissions_Addr: true,
          })
        } else {
          console.log('已授权位置信息')
          that.setData({
            permissions_Addr: false,
          })
        }
      }
    })
  },
  //二次唤起授权位置信息
  authorizedAddress(e) {
    this.isGetSetting()
  },
  onArrshow(e) {
    this.setData({
      permissions_Addr: e.detail
    })
  },
  //推荐商家列表
  getList() {
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true,
    // })
    const that = this
    var data = {
      lnt: this.data.lnt, //经度 
      lat: this.data.lat, //纬度
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum,
      city: this.data.areaCode,
      queryType: this.data.queryType,
    }
    WXAPI.cardAllList(data, (res) => {
      const {
        size,
        total,
        records
      } = res.result
      var list = []
      var cardList = this.data.cardList

      if (res.code === 200) {
        if (this.data.pageNum >= Math.ceil(total / size)) {
          this.setData({
            lodingtype: 1,
            isPull: false,
          })
        } else {
          this.setData({
            lodingtype: 0,
            isPull: true,
          })
        }
        // wx.hideLoading()
        list = records,
          this.setData({
            cardList: cardList.concat(list),
          })
      }
    })
  },
  //政策列表
  handlePolicy() {
    wx.navigateTo({
      url: '/userPageB/pages/userMarket/policyList/policyList',
    })
  },
  handleAnnouncement() {
    wx.navigateTo({
      url: '/userPageB/pages/userMarket/announcementList/announcementList',
    })
  },
  //监管首页
  handleRegulatory() {
    wx.navigateTo({
      url: '/userPageB/pages/userMarket/regulatory/regulatory',
    })
  },
  //唤醒扫一扫功能
  getScancode: function () {
    var that = this;
    // 允许从相机和相册扫码
    wx.scanCode({
      success: (res) => {
        console.log(res.result)
        let parameter = res.result.split("code=")[1];
        console.log(parameter)
        if (parameter==undefined) {
          setTimeout(()=>{
            wx.showToast({
              title: '无效的二维码',
              icon:'none',
            })
          },800)
          return
        }
        let result = JSON.parse(parameter)
        console.log(result)
        console.log("扫一扫参数", result.param)
        console.log("扫一扫类型", result.type)
        console.log("扫一扫类型", result.staffId)
        if (result.type == 1) {
          wx.navigateTo({
            url: '/userPageA/pages/scan/information/information?param=' + result.param
          })
        } else if (result.type == 2) {
          wx.navigateTo({
            url: '/userPageA/pages/scan/receiving_assets/receiving_assets?param=' + result.param
          })
        } else if (result.type == 4) {
          this.setData({
            qrCodeUrl: result.param,
            staffId: result.staffId
          })
          this.getParCollectionQrCodeUrl()
        } else if (result.type == 5) { //退卡页面
          wx.navigateTo({
            url: '/userPageB/pages/returnCard/returnCard?param=' + result.param
          })
        } else {
          console.log('else')
          setTimeout(()=>{
            wx.showToast({
              title: '无效的二维码',
              icon:'none',
            })
          },800)
        }
      },
      fail: (res) => {
        console.log(res)
        if (res.errMsg=='scanCode:fail') {
          setTimeout(()=>{
            wx.showToast({
              title: '无效的二维码',
              icon:'none',
            })
          },800)
        }
      }
    })
  },
  //解析二维码confirmInfo
  getParCollectionQrCodeUrl() {

    var data = {
      qrCodeUrl: this.data.qrCodeUrl,
    }
    WXAPIOLD.parCollectionQrCodeUrl(data, (res) => {
      const data = res.result
      console.log("解析二维码", res)
      if (res.code === 200) {
        var merchantId = data.merchantId
        console.log('this.data.staffId', this.data.staffId)
        wx.navigateTo({
          // url: '/pages/pay/pay?QRmerchantId='+merchantId,   
          url: '/pages/pay/payTransit/payTransit?QRmerchantId=' + merchantId + '&staffId=' + this.data.staffId,
        })
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
      }
    })
  },
  // 通过获取系统信息计算导航栏高度
  setNavSize: function () {
    var that = this,
      sysinfo = wx.getSystemInfoSync(),
      statusHeight = sysinfo.statusBarHeight,
      isiOS = sysinfo.system.indexOf('iOS') > -1,
      navHeight;
    var height = wx.getSystemInfoSync().windowHeight

    if (!isiOS) {
      navHeight = 48;
    } else {
      navHeight = 44;
    }
    height = height - statusHeight - navHeight
    console.log('height', height)
    console.log('statusHeight', statusHeight)
    console.log('navHeight', navHeight)
    that.data.top = statusHeight + navHeight
    that.setData({
      status: statusHeight,
      navHeight: navHeight,
      scroll_height: height + "px",
    })
  },
  view_height: function () {
    let that = this
    var height = wx.getSystemInfoSync().windowHeight
    console.log('hahahahah', height)
    that.setData({
      scroll_height: height + "px",
    })
  },
  //滚动监听
  scroll: function (e) {
    var that = this;
    var scrollY = e.detail.scrollTop
    // console.log(scrollY)
    if (scrollY > 300) {
      that.setData({
        scrollY: true,
      })
      // wx.setNavigationBarColor({
      //   frontColor: '#000000',
      //   backgroundColor: '#000000',
      // })
    } else if (scrollY < 300) {
      that.setData({
        scrollY: false,
      })
      // wx.setNavigationBarColor({
      //   frontColor: '#ffffff',
      //   backgroundColor: '#ffffff',
      // })
    }

  },

  bindDownLoad: function () {
    if (this.data.isPull == true) {
      var pageNum = this.data.pageNum
      pageNum++
      console.log("触底了", pageNum)
      this.setData({
        pageNum: pageNum
      });
      this.getList()
    }
  },
  //签约保险说明弹窗
  signedView(){
    this.setData({
      tipShow: true
    })
  },
  //资金监管弹窗
  superviseTipView(e){
    let num = e.currentTarget.dataset.superviseratio
    this.setData({
      superviseTipShow: true,
      superviseRatio: num
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },


  /** 页面上拉触底事件的处理函数   */

  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})